//
//  LoginViewController.m
//  location
//
//  Created by Dongxiang Xu on 2024/4/15.
//

#import "LoginViewController.h"
#import "XDXBaseTabBarViewController.h"
#import "PolicyWebViewController.h"
#import "InputPhoneViewController.h"
#import "RegisterConfigViewController.h"
#import "SDCycleScrollView.h"
#import <AuthenticationServices/AuthenticationServices.h>
#import "WXApi.h"

@interface LoginViewController ()<ASAuthorizationControllerDelegate>

@property (nonatomic,strong) UITextField *userName;
@property (nonatomic,strong) UITextField *passWord;
@property (nonatomic,strong) UIButton *dotButton;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
                   
    self.navigationController.navigationItem.leftItemsSupplementBackButton = NO;
    self.navigationController.interactivePopGestureRecognizer.delegate = (id<UIGestureRecognizerDelegate>)self;
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 0, 44, 44);                     // 控制触摸区域
    [backBtn setImage:[UIImage imageNamed:@"nav_back"] forState:UIControlStateNormal];
    [[backBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [self.navigationController.navigationBar addSubview:backBtn];
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self initView];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(WXLogin:) name:Noti_WXLogin object:nil];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)initView
{
    UIImageView *loginBg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH*1.83)];
    loginBg.image = [UIImage imageNamed:@"login_bg"];
    [self.view addSubview:loginBg];
    
    NSArray *bannerArray = @[@{@"title":@"走出家门",@"subTitle":@"家人相伴左右",@"img":@"login_0",@"rect":[NSValue valueWithCGRect:CGRectMake((SCREEN_WIDTH-260)/2, 82, 260, 256)],@"color":[UIColor colorWithRed:56/255.0 green:61/255.0 blue:114/255.0 alpha:1/1.0]},
                             @{@"title":@"多种策略",@"subTitle":@"保护家人安全",@"img":@"login_1",@"rect":[NSValue valueWithCGRect:CGRectMake((SCREEN_WIDTH-240)/2, 70, 240, 268)],@"color":[UIColor colorWithRed:68/255.0 green:43/255.0 blue:81/255.0 alpha:1/1.0]},
                             @{@"title":@"无论在哪",@"subTitle":@"感受安心和爱",@"img":@"login_2",@"rect":[NSValue valueWithCGRect:CGRectMake((SCREEN_WIDTH-260)/2, 78, 260, 260)],@"color":[UIColor colorWithRed:68/255.0 green:45/255.0 blue:0/255.0 alpha:1/1.0]}];
    NSMutableArray *bannerImg = [NSMutableArray array];
    for (int i=0 ; i<bannerArray.count; i ++) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 456)];
        
        UIImageView *img = [[UIImageView alloc] initWithFrame:[bannerArray[i][@"rect"] CGRectValue]];
        img.image = [UIImage imageNamed:bannerArray[i][@"img"]];
        [view addSubview:img];
                       
        UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(0, img.maxY+50, SCREEN_WIDTH, 34)];
        title.textColor = RealBlackColor;
        title.textAlignment = NSTextAlignmentCenter;
        title.text = bannerArray[i][@"title"];
        title.font = DEFAULT_FONT(24);
        [view addSubview:title];
        
        UILabel *subTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, title.maxY, SCREEN_WIDTH, 34)];
        subTitle.textColor = bannerArray[i][@"color"];
        subTitle.textAlignment = NSTextAlignmentCenter;
        subTitle.text = bannerArray[i][@"subTitle"];
        subTitle.font = MEDIUM_FONT(24);
        [view addSubview:subTitle];
        
        [bannerImg addObject:[self captureView:view]];
    }
    
    
    SDCycleScrollView *banner = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, STATUSHEIGHT, SCREEN_WIDTH, 504) imagesGroup:bannerImg];
    banner.autoScrollTimeInterval = 6.0;
    banner.dotColor = NormalMainColor;
    [self.view addSubview:banner];
    
    _dotButton = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_WIDTH-280)/2, SCREEN_HEIGHT-70, 32, 32)];
    [_dotButton setImage:[UIImage imageNamed:@"agree_nor"] forState:UIControlStateNormal];
    [_dotButton setImage:[UIImage imageNamed:@"agree_sel"] forState:UIControlStateSelected];
    [self.view addSubview:_dotButton];
    [[_dotButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        self.dotButton.selected = !self.dotButton.selected;
    }];
    
    UILabel *agreeLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.dotButton.frame), SCREEN_HEIGHT-62, 248, 18)];
    agreeLabel.userInteractionEnabled = YES;
    agreeLabel.textColor = GraryTooHeavyColor;
    agreeLabel.font = DEFAULT_FONT(13);
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"我已阅读并同意《用户协议》和《隐私政策》"];
    [str addAttribute:NSForegroundColorAttributeName value:GraryHeavyLightColor range:NSMakeRange(7, 6)];
    [str addAttribute:NSForegroundColorAttributeName value:GraryHeavyLightColor range:NSMakeRange(14, 6)];
    agreeLabel.attributedText = str;
    [self.view addSubview:agreeLabel];
    
    UIButton *agreeButton = [[UIButton alloc] initWithFrame:CGRectMake(95, 0, 65, agreeLabel.height)];
    [agreeLabel addSubview:agreeButton];
    [[agreeButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        PolicyWebViewController *vc = [[PolicyWebViewController alloc] initWithRelativePath:@"http://m.tanhuos.com/user_agreement.html"];
        vc.modalPresentationStyle = UIModalPresentationPageSheet;
        [self presentViewController:vc animated:YES completion:nil];
    }];
    
    UIButton *privacyButton = [[UIButton alloc] initWithFrame:CGRectMake(agreeButton.maxX+22, 0, 65, agreeLabel.height)];
    [agreeLabel addSubview:privacyButton];
    [[privacyButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        PolicyWebViewController *vc = [[PolicyWebViewController alloc] initWithRelativePath:@"http://m.tanhuos.com/privacy_policy.html"];
        vc.modalPresentationStyle = UIModalPresentationPageSheet;
        [self presentViewController:vc animated:YES completion:nil];
    }];
    
    NSArray *array = @[@{@"title":@" 手机登录",@"icon":@"phone_icon"},@{@"title":@" 通过 Apple 登录",@"icon":@"apple_icon"}];
    for (int i=0; i<array.count; i ++) {
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(41+i*((SCREEN_WIDTH-90)/2+10), agreeLabel.y-93, (SCREEN_WIDTH-90)/2, 52)];
        [button setTitle:array[i][@"title"] forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:array[i][@"icon"]] forState:UIControlStateNormal];
        button.layer.masksToBounds = YES;
        [button.layer setCornerRadius:16];
        [button.titleLabel setFont:REAL_MEDIUM_FONT(14)];
        [self.view addSubview:button];
        [button.layer setBorderWidth:1];
        [button.layer setBorderColor:[RealBlackColor colorWithAlphaComponent:0.1].CGColor];
        [button setTitleColor:GraryHeavyLightColor forState:UIControlStateNormal];
        [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            if (self.dotButton.selected==NO) {
                [self initAgreeViewWithIndex:i];
            }else{
                if (i==0) {
                    InputPhoneViewController *vc = [[InputPhoneViewController alloc] init];
                    [self.navigationController pushViewController:vc animated:YES];
                }else if (i==1){
                    if (@available(iOS 13.0, *)) {
                        ASAuthorizationAppleIDProvider * appleIDProvider = [[ASAuthorizationAppleIDProvider alloc] init];
                        ASAuthorizationAppleIDRequest * authAppleIDRequest = [appleIDProvider createRequest];
                        authAppleIDRequest.requestedScopes = @[ASAuthorizationScopeFullName, ASAuthorizationScopeEmail];
                        NSMutableArray <ASAuthorizationRequest *> * array = [NSMutableArray arrayWithCapacity:1];
                        if (authAppleIDRequest) {
                            [array addObject:authAppleIDRequest];
                        }
                        
                        NSArray <ASAuthorizationRequest *> * requests = [array copy];
                        ASAuthorizationController * authorizationController = [[ASAuthorizationController alloc] initWithAuthorizationRequests:requests];
                        authorizationController.delegate = self;
                        [authorizationController performRequests];
                    }
                }
            }
        }];
    }
    
    for (int i = 0; i < 2; i ++) {
        UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(41+i*((SCREEN_WIDTH-132)/2+50), agreeLabel.y-120, (SCREEN_WIDTH-132)/2, 1)];
        line.image = [UIImage imageNamed:@"line"];
        [self.view addSubview:line];
    }
    
    UILabel *or = [[UILabel alloc] initWithFrame:CGRectMake((SCREEN_WIDTH-50)/2, agreeLabel.y-134, 50, 29)];
    or.textAlignment = NSTextAlignmentCenter;
    or.textColor = GraryTooHeavyColor;
    or.font = DEFAULT_FONT(13);
    or.text = @"或";
    [self.view addSubview:or];
    
    UIButton *wx = [[UIButton alloc] initWithFrame:CGRectMake(41, agreeLabel.y-197, SCREEN_WIDTH-82, 52)];
    wx.backgroundColor = NormalMainColor;
    wx.layer.masksToBounds = YES;
    [wx.layer setCornerRadius:16];
    [wx setImage:[UIImage imageNamed:@"wx_icon"] forState:UIControlStateNormal];
    [wx.titleLabel setFont:REAL_MEDIUM_FONT(14)];
    [wx setTitle:@" 微信登录" forState:UIControlStateNormal];
    [wx setTitleColor:RealWhiteColor forState:UIControlStateNormal];
    [self.view addSubview:wx];
    [[wx rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        if (self.dotButton.selected==NO) {
            [self initAgreeViewWithIndex:2];
        }else{
            if ([WXApi isWXAppInstalled]){
                SendAuthReq *req = [[SendAuthReq alloc] init];
                req.state = @"wx_oauth_authorization_state";
                req.scope = @"snsapi_userinfo";
                [WXApi sendReq:req completion:nil];
            }
        }
    }];
}

#pragma mark- ASAuthorizationControllerDelegate
// 授权成功
- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithAuthorization:(ASAuthorization *)authorization
API_AVAILABLE(ios(13.0))
{
    if ([authorization.credential isKindOfClass:[ASAuthorizationAppleIDCredential class]]) {
        ASAuthorizationAppleIDCredential *credential = (ASAuthorizationAppleIDCredential *)authorization.credential;
        NSString *identityTokenString = credential.identityToken ? [[NSString alloc] initWithData:credential.identityToken encoding:NSUTF8StringEncoding] : @"";
        NSString *authorizationCodeString = credential.authorizationCode ? [[NSString alloc] initWithData:credential.authorizationCode encoding:NSUTF8StringEncoding] : @"";

        NSMutableDictionary *param = [[NSMutableDictionary alloc] init];
        [param setValue:authorizationCodeString forKey:@"authorizationCode"]; // 服务端换取 token                
        CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
        [manager encryptedPOST:@"/auth/applelogin"
        parameters:param
        success:^(NSDictionary *responseObject) {
            if ([responseObject[@"data"] isKindOfClass:[NSDictionary class]]) {
                [XDXShareInstance shareInstance].access_token = responseObject[@"data"][@"access_token"];
                [[NSUserDefaults standardUserDefaults] setValue:responseObject[@"data"][@"access_token"] forKey:AccessToken];
                [[NSUserDefaults standardUserDefaults] synchronize];
                
                if ([responseObject[@"data"][@"loginStatus"] isEqualToString:@"login"]) {
                    XDXBaseTabBarViewController *tb = [[XDXBaseTabBarViewController alloc] init];
                    [UIApplication sharedApplication].keyWindow.rootViewController = tb;
                    [[UIApplication sharedApplication].keyWindow makeKeyAndVisible];
                }else{
                    RegisterConfigViewController *vc = [[RegisterConfigViewController alloc] init];
                    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
                    [UIApplication sharedApplication].keyWindow.rootViewController = nav;
                    [[UIApplication sharedApplication].keyWindow makeKeyAndVisible];
                }
            }else{
                [[HCToast shareInstance] showToast:[NSString stringWithFormat:@"%@",responseObject[@"msg"]]];
            }
        }
        failure:^(NSError *aError) {
           
        }];
    }
}
// 授权失败
- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithError:(NSError *)error
API_AVAILABLE(ios(13.0)){
    
}

- (void)initAgreeViewWithIndex:(NSInteger)index
{
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    [self.view addSubview:bgView];
    
    UIView *infoView = [[UIView alloc] initWithFrame:CGRectMake(12, SCREEN_HEIGHT, SCREEN_WIDTH-24, 210)];
    [infoView.layer setCornerRadius:26];
    infoView.layer.masksToBounds = YES;
    infoView.backgroundColor = RealWhiteColor;
    [self.view addSubview:infoView];
    
    UIButton *close = [[UIButton alloc] initWithFrame:CGRectMake(infoView.width-46, 16, 30, 30)];
    [close setImage:[UIImage imageNamed:@"map_close"] forState:UIControlStateNormal];
    [infoView addSubview:close];
    [[close rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [UIView animateWithDuration:0.3 animations:^{
            infoView.y = SCREEN_HEIGHT;
            bgView.backgroundColor = [UIColor clearColor];
        } completion:^(BOOL finished) {
            [bgView removeFromSuperview];
            [infoView removeFromSuperview];
        }];
    }];
    
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(0, 40, infoView.width, 28)];
    title.font = MEDIUM_FONT(20);
    title.textColor = RealBlackColor;
    title.textAlignment = NSTextAlignmentCenter;
    title.text = @"请阅读并同意以下条款";
    [infoView addSubview:title];
    
    UILabel *subTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(title.frame)+11, SCREEN_WIDTH, 19)];
    subTitle.font = DEFAULT_FONT(14);
    subTitle.textColor = GraryLightColor;
    subTitle.textAlignment = NSTextAlignmentCenter;
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"《服务条款》和《隐私政策》"];
    [str addAttribute:NSForegroundColorAttributeName value:NormalMainColor range:NSMakeRange(0, 6)];
    [str addAttribute:NSForegroundColorAttributeName value:NormalMainColor range:NSMakeRange(7, str.length-7)];
    subTitle.attributedText = str;
    [infoView addSubview:subTitle];
    
    UIButton *done = [[UIButton alloc] initWithFrame:CGRectMake(32, CGRectGetMaxY(subTitle.frame)+28, infoView.width-64, 54)];
    done.backgroundColor = NormalMainColor;
    done.layer.masksToBounds = YES;
    [done.layer setCornerRadius:24];
    [done.titleLabel setFont:MEDIUM_FONT(16)];
    [done setTitleColor:RealWhiteColor forState:UIControlStateNormal];
    [done setTitle:@"同意并继续" forState:UIControlStateNormal];
    [infoView addSubview:done];
    [[done rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        if (index==0) {
            InputPhoneViewController *vc = [[InputPhoneViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }else if (index==1){
            if (@available(iOS 13.0, *)) {
                ASAuthorizationAppleIDProvider * appleIDProvider = [[ASAuthorizationAppleIDProvider alloc] init];
                ASAuthorizationAppleIDRequest * authAppleIDRequest = [appleIDProvider createRequest];
                authAppleIDRequest.requestedScopes = @[ASAuthorizationScopeFullName, ASAuthorizationScopeEmail];
                NSMutableArray <ASAuthorizationRequest *> * array = [NSMutableArray arrayWithCapacity:1];
                if (authAppleIDRequest) {
                    [array addObject:authAppleIDRequest];
                }
                
                NSArray <ASAuthorizationRequest *> * requests = [array copy];
                ASAuthorizationController * authorizationController = [[ASAuthorizationController alloc] initWithAuthorizationRequests:requests];
                authorizationController.delegate = self;
                [authorizationController performRequests];
            }
        }else if (index==2){
            if([WXApi isWXAppInstalled]){
                SendAuthReq *req = [[SendAuthReq alloc] init];
                req.state = @"wx_oauth_authorization_state";
                req.scope = @"snsapi_userinfo";
                [WXApi sendReq:req completion:nil];
            }
        }
        [UIView animateWithDuration:0.3 animations:^{
            infoView.y = SCREEN_HEIGHT;
            bgView.backgroundColor = [UIColor clearColor];
        } completion:^(BOOL finished) {
            [bgView removeFromSuperview];
            [infoView removeFromSuperview];
            self.dotButton.selected = YES;
        }];
    }];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
    [[tap rac_gestureSignal] subscribeNext:^(id x) {
        [UIView animateWithDuration:0.3 animations:^{
            infoView.y = SCREEN_HEIGHT;
            bgView.backgroundColor = [UIColor clearColor];
        } completion:^(BOOL finished) {
            [bgView removeFromSuperview];
            [infoView removeFromSuperview];
        }];
    }];
    [bgView addGestureRecognizer:tap];
    
    [UIView animateWithDuration:0.3 animations:^{
        infoView.y = SCREEN_HEIGHT-242;
        bgView.backgroundColor = [RealBlackColor colorWithAlphaComponent:0.4];
    }];
}

- (void)WXLogin:(NSNotification *)notify
{
    NSMutableDictionary *param = [[NSMutableDictionary alloc] init];
    [param setValue:notify.userInfo[@"code"] forKey:@"code"];
    CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
    [manager encryptedPOST:@"/auth/wechatlogin"
    parameters:param
    success:^(NSDictionary *responseObject) {
        if ([responseObject[@"data"] isKindOfClass:[NSDictionary class]]) {
            [XDXShareInstance shareInstance].access_token = responseObject[@"data"][@"access_token"];
            [[NSUserDefaults standardUserDefaults] setValue:responseObject[@"data"][@"access_token"] forKey:AccessToken];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            if ([responseObject[@"data"][@"loginStatus"] isEqualToString:@"login"]) {
                XDXBaseTabBarViewController *tb = [[XDXBaseTabBarViewController alloc] init];
                [UIApplication sharedApplication].keyWindow.rootViewController = tb;
                [[UIApplication sharedApplication].keyWindow makeKeyAndVisible];
            }else{
                RegisterConfigViewController *vc = [[RegisterConfigViewController alloc] init];
                UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
                [UIApplication sharedApplication].keyWindow.rootViewController = nav;
                [[UIApplication sharedApplication].keyWindow makeKeyAndVisible];
            }
        }else{
            [[HCToast shareInstance] showToast:[NSString stringWithFormat:@"%@",responseObject[@"msg"]]];
        }
    }
    failure:^(NSError *aError) {
       
    }];
}

- (UIImage *)captureView:(UIView *)view
{
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, 0.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

@end
